package com.bzxgc.sgwer.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * json工具类
 */
public class JsonUtils {

    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * java对象转换json串
     * @param obj
     * @return
     */
    public static String objectToJson(Object obj) {
        String json = null;
        try {
            json = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("java对象转换json串异常失败");
        }
        return json;
    }

    /**
     * json串转换java对象
     * @param json
     * @return
     */
    public static Object jsonToObject(String json) {
        Object obj = null;
        try {
            obj = mapper.readValue(json, Object.class);
        } catch (IOException e) {
            throw new RuntimeException("json串异常转换java对象失败");
        }
        return obj;
    }
}

